package com.easybuilder.core.authorization.controller;

import com.alibaba.fastjson.JSONObject;
import com.easybuilder.common.base.controller.BaseController;
import com.easybuilder.common.utils.JwtUtil;
import com.easybuilder.common.utils.RedisUtil;
import com.easybuilder.common.utils.ServletUtil;
import com.easybuilder.core.authorization.entity.SysGiteeUser;
import com.easybuilder.core.authorization.service.OauthService;
import com.easybuilder.core.authorization.service.impl.GiteeService;
import com.easybuilder.core.rbac.dto.SysUserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/oauth")
public class OauthController extends BaseController {

    @Autowired
    private OauthService oauthService;
    @Autowired
    private GiteeService giteeService;

    @GetMapping("/gitee/redirect")
    public Object authorization(String code) {
        System.out.println(code);
        return code;
    }

    /** 通过三方授权登陆gitee并获取用户信息
     * @param code 用户授权之后，获取到的授权码
     * */
    @PostMapping("/gitee/login")
    public Result<?> loginGitee(@RequestParam(name = "code", required = true) String code){
        // 登陆码云获取用户资料
        SysGiteeUser user = giteeService.login(code);
        // 把码云用户转为系统用户
        SysUserDTO sysUserDTO = convertGiteeUserToSysUser(user);
        // 生成token，并保存用户信息到redis
        String token = JwtUtil.buildToken(sysUserDTO.getUsername(), null, "GITEE");
        // 设置认证信息到响应头中
        ServletUtil.setToken(token);
        // 保存用户信息到redis（redis保存用户信息3小时，token设置有效时间2小时，如果失效时间 < 1小时，达到自动续命的效果）
        RedisUtil.setValue("USER_GITEE_"+sysUserDTO.getUsername(), user, 3L, TimeUnit.HOURS);
        SysGiteeUser value = RedisUtil.getValue("USER_GITEE_" + sysUserDTO.getUsername(), SysGiteeUser.class);
        log.info("redis获取用户信息：" + JSONObject.toJSONString(value));
        return OK(sysUserDTO);
    }

    /** 把码云用户转为系统用户 */
    private SysUserDTO convertGiteeUserToSysUser(SysGiteeUser user) {
        if (user != null) {
            SysUserDTO sysUserDTO = new SysUserDTO();
            sysUserDTO.setId(user.getId());
            sysUserDTO.setUsername(user.getUsername());
            sysUserDTO.setNickname(user.getNickname());
            sysUserDTO.setImg(user.getUserImg());
            return sysUserDTO;
        }
        return null;
    }



}
